//
//  PywRealNameAuthViewController.m
//  PywSdk
//
//  Created by Ampaw on 2017/5/16.
//  Copyright © 2017年 Jade. All rights reserved.
//

#import "PywRealNameAuthViewController.h"
#import <WebKit/WebKit.h>
#import "UIImage+Pyw.h"
#import "PywMasonry.h"
#import "PywAppInfo.h"
#import "PywPlatformMain.h"
#import "MutableDictionary.h"
#import "AppUtil.h"
#import "PywRealNameAuthManager.h"

@interface webAuthSdkObj:NSObject<RealNameAuthProtocol>
@property (nonatomic,strong) PywRealNameAuthViewController *controller;
- (instancetype)initWithController:(PywRealNameAuthViewController *)controller;
@end
@implementation webAuthSdkObj

- (instancetype)initWithController:(PywRealNameAuthViewController *)controller
{
    self = [super init];
    if (self) {
        self.controller = controller;
    }
    return self;
}

- (void)onSuccess
{
    self.controller.isVerify = YES;
    PLog(@"成功%d",self.controller.isVerify);
}

- (void)onfail
{
    self.controller.isVerify = NO;
    PLog(@"失败！%d",self.controller.isVerify);
}

- (void)onCloseWindow
{
    PLog(@"关闭弹框%d",self.controller.isVerify);
    [[PywRealNameAuthManager manager] dismissViewController:self.controller
                                                   isVerify:self.controller.isVerify];
}

@end

@interface PywRealNameAuthViewController ()<UIWebViewDelegate>
@property (nonatomic, strong) UIWebView *webView;
@end

@implementation PywRealNameAuthViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    [self setUp];
}

- (void)setUp
{
    self.automaticallyAdjustsScrollViewInsets = YES;
    self.navigationController.interactivePopGestureRecognizer.enabled = NO; // 禁止系统的手势返回
    
    [self.view addSubview:self.webView];
    __weak typeof(self) weakSelf = self;
    [weakSelf.webView mas_makeConstraints:^(PywMASConstraintMaker *make) {
        make.top.bottom.right.left.offset(0);
    }];
    [self requestRealNameAuth];
}

#pragma mark - UIWebViewDelegate
- (void)webViewDidFinishLoad:(UIWebView *)webView
{
    //JS-->:window.sdkObj.doSdkExit 接收JS调用OC
    JSContext *context = [self.webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];
    context.exceptionHandler =
    ^(JSContext *context, JSValue *exceptionValue)
    {
        context.exception = exceptionValue;
        NSLog(@"exceptionValue:%@", exceptionValue);
    };
    webAuthSdkObj *sdkObj = [[webAuthSdkObj alloc] initWithController:self];
    context[@"sdkObj"] = sdkObj;
}

/**
 请求实名认证
 */
- (void)requestRealNameAuth
{
    NSString *gameid = [PywAppInfo sharedAppInfo].gameId;
    NSString *userName = [PywPlatformMain sharedPlatformMain].userName;
    NSString *token = [PywPlatformMain sharedPlatformMain].passport_Token.length > 0 ? [PywPlatformMain sharedPlatformMain].passport_Token : [PywPlatformMain sharedPlatformMain].token;
    NSString *imie = [PywAppInfo sharedAppInfo].uuid;
    
    // 请求参数
    MutableDictionary *requestParams = [[MutableDictionary alloc] init];
    [requestParams setObject:userName forKey:@"username"];
    [requestParams setObject:token forKey:@"token"];
    [requestParams setObject:gameid forKey:@"gameid"];
    [requestParams setObject:imie forKey:@"imie"];
    
    // 参数加密,编码为ISO
    NSStringEncoding enc = CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingISOLatin1);
    NSMutableArray *mArray = [[NSMutableArray alloc] init];
    [mArray addObject:requestParams];
    NSData *tmpData = [NSJSONSerialization dataWithJSONObject:mArray options:0 error:nil];
    NSData *testData = [AppUtil encode:tmpData];
    NSString *dataStr = [[NSString alloc] initWithData:testData encoding:enc];
    NSString *param = [self encodeString:dataStr];
    
    // 参数添加到“请求头”传入请求，请求头参数字段为：param
    NSURLRequest *request = [[NSURLRequest alloc] initWithURL:[NSURL URLWithString:shiMingRenZhengUrl]
                                                  cachePolicy:NSURLRequestReloadIgnoringCacheData
                                              timeoutInterval:20];
    NSMutableURLRequest *mutableRequest = [request mutableCopy];
    [mutableRequest addValue:param forHTTPHeaderField:@"param"];
    request = [mutableRequest copy];
    [self.webView loadRequest:request];
}

/**
 对加密数据进行URLEnCode转码，编码为ISO

 @param unencodedString 加密数据
 */
- (NSString*)encodeString:(NSString*)unencodedString
{
    NSString*encodedString = (NSString*)CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,
                                                                                                  (CFStringRef)unencodedString,
                                                                                                  NULL,
                                                                                                  (CFStringRef)@"!*'();:@&=+$,/?%#[]",
                                                                                                  kCFStringEncodingISOLatin1));
    return encodedString;
}

#pragma mark - Lazy
- (UIWebView *)webView
{
    if (!_webView) {
        _webView = [[UIWebView alloc] init];
        _webView.delegate = self;
        _webView.scalesPageToFit = YES;
    }
    return _webView;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
